package com.xkstream.client.ui;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xkstream.client.R;
import com.xkstream.client.api.API;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.entity.Area;
import com.xkstream.client.entity.UploadImg;
import com.xkstream.client.http.FileUploadUtil;
import com.xkstream.client.presenter.RegisterContract;
import com.xkstream.client.presenter.RegisterPresenter;
import com.xkstream.client.utils.AsyncImage;
import com.xkstream.client.utils.BitmapUtil;
import com.xkstream.client.view.BottomPushPopupWindow;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by admin on 2017/5/3.
 */

public class RegisterActivity extends BaseActivity<RegisterContract.Presenter> implements RegisterContract.View {
    @BindView(R.id.edtAccount)
    EditText edtAccount;
    @BindView(R.id.edtMail)
    EditText edtMail;
    @BindView(R.id.btnRigster)
    Button btnRigster;
    @BindView(R.id.ivUploadHeader)
    ImageView ivUploadHeader;
    @BindView(R.id.ivWithoutMakeup)
    ImageView ivWithoutMakeup;
    @BindView(R.id.ivMakeup)
    ImageView ivMakeup;
    @BindView(R.id.ivArtPhoto)
    ImageView ivArtPhoto;
    @BindView(R.id.tvAgency)
    TextView tvAgency;

    private static final int CAMERA_HEADER = 1;
    private static final int PHOTO_HEADER = 2;
    private static final int CAMERA_WITHOUTMAKEUP = 3;
    private static final int PHOTO_WITHOUTMAKEUP = 4;
    private static final int CAMERA_MAKEUP = 5;
    private static final int PHOTO_MAKEUP = 6;
    private static final int CAMERA_ARTPHOTO = 7;
    private static final int PHOTO_ARTPHOTO = 8;

    private UploadImg headIcon;
    private UploadImg lowIcon;
    private UploadImg midIcon;
    private UploadImg higIcon;

    private static final String HEADNAME = "head_icon";
    private static final String LOWNAME = "low_pic";
    private static final String MIDNAME = "mid_pic";
    private static final String HIGNAME = "hig_pic";

    private HashMap<String, String> params = new HashMap<>();


    private Context context;

    public static final String EMAIL_FORMAT = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_register);
        context = this;
        ButterKnife.bind(this);
        presenter = new RegisterPresenter(this);
    }

    @OnClick({R.id.rlUploadHeader, R.id.rlWithoutMakeUp, R.id.rlMakeUp, R.id.rlArtPhoto, R.id.ivClose, R.id.btnRigster, R.id.tvAgency})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlUploadHeader:
                createSelectPhotoDialog(0);
                break;
            case R.id.rlWithoutMakeUp:
                createSelectPhotoDialog(1);
                break;
            case R.id.rlMakeUp:
                createSelectPhotoDialog(2);
                break;
            case R.id.rlArtPhoto:
                createSelectPhotoDialog(3);
                break;
            case R.id.ivClose:
                break;
            case R.id.btnRigster:
                registerAnchor();
                break;
            case R.id.tvAgency:
                Intent intent = new Intent();
                intent.setClass(context, AreaCodeActivity.class);
                startActivityForResult(intent, 0);
                break;
        }
    }

    private void createSelectPhotoDialog(final int type) {
        final BottomPushPopupWindow popupWindow = new BottomPushPopupWindow(context, 0);
        popupWindow.show(this);
        View view = popupWindow.getContentView();
        TextView tvCamera = (TextView) view.findViewById(R.id.tvCamera);
        TextView tvPhoto = (TextView) view.findViewById(R.id.tvPhoto);
        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                if (type == 0) {
                    startActivityForResult(intent, CAMERA_HEADER);
                } else if (type == 1) {
                    startActivityForResult(intent, CAMERA_WITHOUTMAKEUP);
                } else if (type == 2) {
                    startActivityForResult(intent, CAMERA_MAKEUP);
                } else if (type == 3) {
                    startActivityForResult(intent, CAMERA_ARTPHOTO);
                }
                popupWindow.dismiss();
            }
        });
        tvPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                if (type == 0) {
                    startActivityForResult(intent, PHOTO_HEADER);
                } else if (type == 1) {
                    startActivityForResult(intent, PHOTO_WITHOUTMAKEUP);
                } else if (type == 2) {
                    startActivityForResult(intent, PHOTO_MAKEUP);
                } else if (type == 3) {
                    startActivityForResult(intent, PHOTO_ARTPHOTO);
                }
                popupWindow.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case -1:
                if (data != null) {
                    //取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意
                    Uri mImageCaptureUri = data.getData();
                    //返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取
                    if (mImageCaptureUri != null) {
                        Bitmap image;
                        try {
                            //这个方法是根据Uri获取Bitmap图片的静态方法
                            image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri);
                            if (image != null) {
                                String result = BitmapUtil.getPathByUri4kitkat(context, mImageCaptureUri);

                                //      getRealPathFromUri_Api11To18(context, mImageCaptureUri);

                                //      photo.setImageBitmap(image);
                                File outputImage = new File(result);
                                if (requestCode == PHOTO_HEADER) {
                                    uploadUserPhoto(outputImage, HEADNAME);
                                    AsyncImage.loadLocalPhoto(context, result, ivUploadHeader);
                                } else if (requestCode == PHOTO_WITHOUTMAKEUP) {
                                    uploadUserPhoto(outputImage, LOWNAME);
                                    AsyncImage.loadLocalPhoto(context, result, ivWithoutMakeup);
                                } else if (requestCode == PHOTO_MAKEUP) {
                                    uploadUserPhoto(outputImage, MIDNAME);
                                    AsyncImage.loadLocalPhoto(context, result, ivMakeup);
                                } else if (requestCode == PHOTO_ARTPHOTO) {
                                    uploadUserPhoto(outputImage, HIGNAME);
                                    AsyncImage.loadLocalPhoto(context, result, ivArtPhoto);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
                            //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
                            Bitmap image = extras.getParcelable("data");

                            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                            Date date = new Date(System.currentTimeMillis());
                            String filename = format.format(date);
                            // 创建File对象用于存储拍照的图片 SD卡根目录
                            // File outputImage = new
                            // File(Environment.getExternalStorageDirectory(),"test.jpg");
                            // 存储至DCIM文件夹
                            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                            File outputImage = new File(path, filename + ".jpg");
                            try {
                                if (outputImage.exists()) {
                                    outputImage.delete();
                                }
                                outputImage.createNewFile();
                                saveBitmapFile(image, outputImage);
                                if (requestCode == CAMERA_HEADER) {
                                    if (outputImage != null) {
                                        uploadUserPhoto(outputImage, HEADNAME);
                                    }
                                    AsyncImage.loadLocalPhoto(context, outputImage.getAbsolutePath(), ivUploadHeader);
                                } else if (requestCode == CAMERA_WITHOUTMAKEUP) {
                                    if (outputImage != null) {
                                        uploadUserPhoto(outputImage, LOWNAME);
                                    }
                                    AsyncImage.loadLocalPhoto(context, outputImage.getAbsolutePath(), ivWithoutMakeup);
                                } else if (requestCode == CAMERA_MAKEUP) {
                                    if (outputImage != null) {
                                        uploadUserPhoto(outputImage, MIDNAME);
                                    }
                                    AsyncImage.loadLocalPhoto(context, outputImage.getAbsolutePath(), ivMakeup);
                                } else if (requestCode == CAMERA_ARTPHOTO) {
                                    if (outputImage != null) {
                                        uploadUserPhoto(outputImage, HIGNAME);
                                    }
                                    AsyncImage.loadLocalPhoto(context, outputImage.getAbsolutePath(), ivArtPhoto);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                break;
            case 1:
                Area area = (Area) data.getSerializableExtra("area");
                tvAgency.setText(area.getChain_name());
                tvAgency.setTag(area);
                break;
            default:
                break;

        }
    }

    public void saveBitmapFile(Bitmap bitmap, File outputImage) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputImage));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //将URI转换成FILE
    private File uri2File(Uri uri) {
        File file = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = this.managedQuery(uri, proj, null,
                null, null);
        int actual_image_column_index = actualimagecursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor
                .getString(actual_image_column_index);
        file = new File(img_path);
        return file;
    }

    private void uploadUserPhoto(File file, final String name) {
        try {
            final Map<String, String> fileParams = new HashMap<>();
            fileParams.put("pic", file.getAbsolutePath());
            showLoading("上传中", true);
            //       showToast(getResources().getString(R.string.up_phone));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    FileUploadUtil.uploadImageFile(API.HOST + API.UPLOAD_IMG, null, fileParams, mHandler, name);
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
                    hideLoading();
                    try {
                        String name = (String) msg.obj;
                        Bundle resultData = msg.getData();
                        String result = resultData.getString("result");
                        JSONObject object = new JSONObject(result);
                        String dataStr = object.getString("data");
                        JSONArray list1 = new JSONArray(dataStr);
                        List<UploadImg> list = new Gson().fromJson(dataStr, new TypeToken<List<UploadImg>>() {
                        }.getType());
                        if (list.size() > 0) {
                            UploadImg uploadImg = list.get(0);
                            if (name.equals(HEADNAME)) {
                                headIcon = uploadImg;
                            } else if (name.equals(LOWNAME)) {
                                lowIcon = uploadImg;
                            } else if (name.equals(MIDNAME)) {
                                midIcon = uploadImg;
                            } else if (name.equals(HIGNAME)) {
                                higIcon = uploadImg;
                            }
                        }
                        showToast(getResources().getString(R.string.upload_success));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case FileUploadUtil.FAILED:
                    hideLoading();
                    showToast(getResources().getString(R.string.upload_failed));
                    break;
            }
        }
    };

    private void registerAnchor() {
        params.clear();
        if (headIcon != null) {
            params.put("head_icon", headIcon.getPath());
        } else {
            showToast(getResources().getString(R.string.upload_header));
            return;
        }
        String accountStr = edtAccount.getText().toString();
        if (!TextUtils.isEmpty(accountStr) && accountStr.length() > 0) {
            params.put("nick_name", accountStr);
        } else {
            showToast(getResources().getString(R.string.please_input_nickname));
            return;
        }
        String mailStr = edtMail.getText().toString();

        if (!TextUtils.isEmpty(mailStr) && mailStr.matches(EMAIL_FORMAT)) {
            params.put("email", mailStr);
        } else {
            showToast(getResources().getString(R.string.please_input_email));
            return;
        }
        if (lowIcon != null) {
            params.put("low_pic", lowIcon.getPath());
        } else {
            showToast(getResources().getString(R.string.please_upload_low));
            return;
        }
        if (midIcon != null) {
            params.put("mid_pic", midIcon.getPath());
        } else {
            showToast(getResources().getString(R.string.please_upload_mid));
            return;
        }
        if (higIcon != null) {
            params.put("hig_pic", higIcon.getPath());
        } else {
            showToast(getResources().getString(R.string.please_upload_hig));
            return;
        }
//        if (!TextUtils.isEmpty(tvAgency.getText().toString())) {
//            params.put("channel_code", tvAgency.getText().toString());
//        }
        if (tvAgency.getTag() == null) {
            showToast("请上传地区");
            return;
        } else {
            params.put("anchor_country", tvAgency.getText().toString());
        }
        presenter.anchorRegister(params);
        showLoading();
    }

    @Override
    public void setPresenter(RegisterContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showRegisterResult(BaseData data) {
        if (data.getCode() == 1) {
            showToast(R.string.register_success);
            finish();
        } else {
            showToast(data.getMsg());
        }
    }
}
